﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Genuilder
{
	public static class Projects
	{
		public static IEnumerable<Project> InSubDirectories(string path)
		{
			DirectoryInfo directory = new DirectoryInfo(path);
			foreach(var sub in directory.EnumerateDirectories())
			{
				foreach(var projFile in sub.EnumerateFiles("*csproj"))
				{
					yield return new Project(projFile.FullName);
				}
			}
		}

		
		public static IEnumerable<Project> ExceptForAssembly(this IEnumerable<Project> projects, string assemblyName)
		{
			return projects.Where(p => GetAssemblyName(p) != assemblyName);
		}
		public static IEnumerable<Project> ExceptForAssembly(this IEnumerable<Project> projects, Assembly assembly)
		{
			return ExceptForAssembly(projects, assembly.GetName().Name);
		}
		public static IEnumerable<Project> ExceptForThisAssembly(this IEnumerable<Project> projects)
		{
			return ExceptForAssembly(projects, Assembly.GetCallingAssembly());
		}

		private static string GetAssemblyName(Project project)
		{
			Regex reg = new Regex("<AssemblyName>([^<]+)</AssemblyName>");
			var match = reg.Match(File.ReadAllText(project.Path));
			if(match != null && match.Success)
				return match.Groups[1].Value;
			return null;
		}
	}
}
